package es.uji.viselab.network;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import es.uji.viselab.LogLevel;
import es.uji.viselab.LogRecorder;
import es.uji.viselab.ViSeLabException;

public class networkServerThread extends Thread {
	Server server;
	List<ServerListener> eventListeners = new ArrayList<ServerListener>();

	public networkServerThread(Server server, networkServerThread[] threads) throws ViSeLabException {
		this.server = server;
		server.createReceiver();
		server.createSender();
	}

	public void run() {
      keepReceiving();
	}

	public void keepReceiving() {
		Boolean endConnection = false;

		while (!endConnection) {
			List<DataPackage> data = null;
			try {
				data = server.receiveAndDecodeData();
			} catch (ViSeLabException e) {
				e.printStackTrace();
			}
			if (data != null) {
				Iterator<DataPackage> iterator = data.iterator();
				while (iterator.hasNext()) {
					DataPackage item = iterator.next();
					// System.out.println(item.print());
					notifyDataArrival(item);
					// database.insert(item);
				}

			} else {
				LogRecorder.log(LogLevel.INFO, "Closing connection from "
						+ server.getServiceSocket().getInetAddress().getHostAddress());
				try {
					endConnection = true;
					server.closeConnection();
				} catch (ViSeLabException e) {
					e.printStackTrace();
					// throw new
					// BMException("Error while trying to close the connection","NetworkServerThread.run(); ");
				}
			}
		}
	}

	private void receive() {

		List<DataPackage> data = null;
		try {
			data = server.receiveAndDecodeData();
		} catch (ViSeLabException e) {
			e.printStackTrace();
		}
		if (data != null) {
			Iterator<DataPackage> iterator = data.iterator();
			while (iterator.hasNext()) {
				DataPackage item = iterator.next();
				// System.out.println(item.print());
				notifyDataArrival(item);
				// database.insert(item);
			}
		}
	}

	private void notifyDataArrival(DataPackage dn) {
		Iterator<ServerListener> iterator = eventListeners.iterator();
		while (iterator.hasNext()) {
			ServerListener sl = iterator.next();
			sl.newIncommingMessage(dn);
		}

	}

	public void addListener(ServerListener sl) {
		eventListeners.add(sl);
	}

	public void sendData(DataPackage item) {
		server.encodeAndSendData(item);

	}

}
